package com.chris.autoconfiguration.jedis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableConfigurationProperties(JedisProperties.class)
// 取jedis.enable的配置和 havingValue 后的值对比 相同的话则生效启用 matchIfMissing=false表示默认不配置jedis.enable不生效
@ConditionalOnProperty(prefix = "jedis", name = "enable", havingValue = "true", matchIfMissing = false)
public class JedisAutoConfiguration {

    @Autowired
    private JedisProperties properties;

    @Bean
    @ConditionalOnMissingBean(JedisPool.class)
    public JedisPool jedisPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMinIdle(properties.getMinIdle());
        config.setMaxIdle(properties.getMaxIdle());
        config.setMaxTotal(properties.getMaxTotal());
        JedisPool pool = new JedisPool(config,
                properties.getHost(),
                properties.getPort(),
                properties.getTimeout(),
                properties.getPassword());
        return pool;
    }


    @Bean
    @ConditionalOnMissingBean(JedisCore.class)
    public JedisCore jedisCore(JedisPool jedisPool) {
        JedisCore jedisCore = new JedisCore(jedisPool);
        return jedisCore;
    }


}
